import http from 'http'
import VM from 'vm'
import { error } from './output.js'

const routes = {}

export default {
  println: (...args) => {
    const _arguments = args.map((arg) => {
      if (arg === undefined || arg === null) return `<'none'>`
      if (typeof arg === 'function') return `<'fun'>`
      return arg
    })
    process.stdout.write(_arguments.join(' ') + '\n')
  },
  print: (...args) => {
    const _arguments = args.map((arg) => {
      if (arg === undefined || arg === null) return `<'none'>`
      if (typeof arg === 'function') return `<'fun'>`
      return arg
    })
    process.stdout.write(_arguments.join(' '))
  },
  sleep: (ms) => {
    return new Promise((resolve) => {
      setTimeout(resolve, ms)
    })
  },
  time: () => {
    return Date.now()
  },
  localtime: (timestamp) => {
    return new Date(timestamp).toLocaleString()
  },
  listen: (hostname, port, callback) => {
    try {
      const server = http.createServer((req, res) => {
        const route = routes[req.url]
        if (route === undefined) {
          res.writeHead(404)
          res.end()
          return
        }
        if (req.method !== route.method) {
          res.writeHead(405)
          res.end()
          return
        }
        res.writeHead(200, { 'Content-Type': route.type })
        res.end(route.body)
      })
      server.listen(port, hostname, callback)
    } catch (err) {
      error(`Error while listening: '${ err }'`)
    }
  },
  get(url, type, body) {
    routes[url] = {
      method: 'GET',
      type,
      body
    }
  },
  post(url, type, body) {
    routes[url] = {
      method: 'POST',
      type,
      body
    }
  },
  exec(script) {
    try {
      return VM.runInNewContext(script, {})
    } catch (err) {
      error(`Error while executing script: '${ err }'`)
    }
  }
}
